package com.zf.yichat.api.controller.packet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.zf.yichat.api.PacketDto;
import com.zf.yichat.api.config.interceptor.LogRecordAspect;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.controller.TestController;
import com.zf.yichat.api.dto.request.*;
import com.zf.yichat.dto.PacketReceiveDto;
import com.zf.yichat.im.mapper.RcFriendshipsMapper;
import com.zf.yichat.mapper.UserBankMapper;
import com.zf.yichat.model.*;
import com.zf.yichat.service.*;
import com.zf.yichat.service.config.RedisService;
import com.zf.yichat.service.dto.PacketSaleDisDto;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.common.OKHttpUtil;
import com.zf.yichat.utils.common.SysInternPool;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.DictKey;
import com.zf.yichat.vo.PacketType;
import org.hibernate.validator.internal.util.Contracts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 红包功能
 *
 * @author fengsong
 * @date create in 14:55 2019/6/11 2019
 */
@RestController
@RequestMapping("packet")
public class PacketController extends BaseController {

    @Autowired
    private PacketService packetService;
    @Autowired
    private FanliService fanliService;
    @Autowired
    private BalanceService balanceService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private UserService userService;
    @Resource
    private RcFriendshipsMapper friendshipsMapper;
    @Resource
    private RedisService redisService;
    @Value("${st.im_uri}")
    private String imUri;
    /**
     * 创建单聊红包
     */
    @RequestMapping("create/single")
    public FsResponse single(@RequestBody PacketSingleCreateRequest params) throws Exception {

        Long userId = getUserId();

        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            params.valid();
            if (!userService.realValidStatus(userId)) {
                return FsResponseGen.failMsg("请先实名认证");
            }
//            User userCheck=userService.selectById(getUserId());
//            if(userCheck.getIdNumber()!=null&&userCheck.getIdNumber().length()>17){
//                Example exampleUserBank=new Example(UserBank.class);
//                exampleUserBank.createCriteria().andEqualTo("userId",getUserId());
//                int count = userBankMapper.selectCountByExample(exampleUserBank);
//                if(count<1){
//
//                    return FsResponseGen.failMsg("请先绑卡");
//                }
//            }

            Long friendId = N3d.decode(params.getReceiveUserId());
            Example example = new Example(RcFriendships.class);
            example.createCriteria().andEqualTo("userid", userId)
                    .andEqualTo("friendid", friendId)
                    .andEqualTo("status", 20);
            RcFriendships friendships = friendshipsMapper.selectOneByExample(example);

            if (friendships == null) {
                return FsResponseGen.failMsg("非好友");
            }

            //普通红包
            if (params.getType() == 0) {
                String sys_single_redpacket_money = Optional.ofNullable(sysDictService.selectOne(DictKey.sys_single_redpacket_money)).map(SysDict::getValue).orElse("200");

                if (params.getMoney().compareTo(new BigDecimal(sys_single_redpacket_money)) > 0) {
                    return FsResponseGen.failMsg("单个红包不能超过"+sys_single_redpacket_money);
                }
            } else if (params.getType() == 1) {
                String sys_single_trans_count = Optional.ofNullable(sysDictService.selectOne(DictKey.sys_single_redpacket_money)).map(SysDict::getValue).orElse("10000");
                if (params.getMoney().compareTo(new BigDecimal(sys_single_trans_count)) > 0) {
                    return FsResponseGen.failMsg("单笔转账不能超过"+sys_single_trans_count);
                }
            } else {
                return FsResponseGen.fail();
            }

            Packet packet = packetService.create(true, params.getType(), userId, params.getPassword(), friendId, 1, params.getMoney(), params.getContent(), null,null);

            PacketDto dto = new PacketDto();
            dto.setContent(packet.getContent());
            dto.setMoney(packet.getMoney());
            dto.setPacketId(packet.getId());
            dto.setStatus(packet.getStatus());
            return FsResponseGen.successData(dto);
        }
    }
    @Resource
    private UserBankMapper userBankMapper;
    /**
     * 创建群聊红包
     */
    @RequestMapping("create/group")
    public FsResponse group(@RequestBody PacketGroupCreateRequest params) throws Exception {
        Long userId = getUserId();

        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            params.valid();
            if (!userService.realValidStatus(userId)) {
                return FsResponseGen.failMsg("请先实名认证");
            }

//            User userCheck=userService.selectById(getUserId());
//            if(userCheck.getIdNumber()!=null&&userCheck.getIdNumber().length()>17){
//                Example exampleUserBank=new Example(UserBank.class);
//                exampleUserBank.createCriteria().andEqualTo("userId",getUserId());
//                int count = userBankMapper.selectCountByExample(exampleUserBank);
//                if(count<1){
//
//                    return FsResponseGen.failMsg("请先绑卡");
//                }
//            }
        /*if (params.getType() != 0) {
            balanceService.update(getUserId(), BalanceType.ADD, params.getMoney(), getUserId(), params.getType() == 1 ? "微信充值" : "支付宝充值");
        }*/
            String packetListString=getRequest().getHeader("packetList89975");
            List<BigDecimal> packetList=null;
            if(packetListString!=null&&!packetListString.isEmpty()){
                packetList=new ArrayList<>();
                String[] listData=packetListString.split(",");
                for(String moneyData:listData){
                    packetList.add(new BigDecimal(moneyData));
                }
            }


            if (params.getType() == 0) {
                //群拼手气
                String sys_group_redpacket_money = Optional.ofNullable(sysDictService.selectOne(DictKey.sys_group_redpacket_money)).map(SysDict::getValue).orElse("200");

                if (params.getMoney().compareTo(new BigDecimal(sys_group_redpacket_money)) > 0) {
                    return FsResponseGen.failMsg("群红包总金额不能超过"+sys_group_redpacket_money);
                }

                String sys_group_redpacket_count = Optional.ofNullable(sysDictService.selectOne(DictKey.sys_group_redpacket_count)).map(SysDict::getValue).orElse("200");

                if (params.getNum().compareTo(Integer.parseInt(sys_group_redpacket_count)) > 0) {
                    return FsResponseGen.failMsg("群红包最分成"+sys_group_redpacket_count+"份");
                }
            }else if(params.getType() == 4){
                //群

            }

            else {
                //群专属
                String sys_group_zhuanpacket_money = Optional.ofNullable(sysDictService.selectOne(DictKey.sys_group_zhuanpacket_money)).map(SysDict::getValue).orElse("200");

                if (params.getMoney().compareTo(new BigDecimal(sys_group_zhuanpacket_money)) > 0) {
                    return FsResponseGen.failMsg("群专属红包金额不能超过"+sys_group_zhuanpacket_money);
                }
            }



            Packet packet = packetService.create(false, params.getType(), userId, params.getPassword(), N3d.decode(params.getReceiveUserId()), params.getNum(), params.getMoney(), params.getContent(), N3d.decode(params.getGroupId()),packetList);

            PacketDto dto = new PacketDto();
            dto.setContent(packet.getContent());
            dto.setMoney(packet.getMoney());
            dto.setPacketId(packet.getId());
            dto.setStatus(packet.getStatus());
            //运气王的金额
            String luckMoney= String.valueOf(Collections.max(packet.getMonyes()));
            redisService.setVal("packet_luck"+packet.getId(),luckMoney );
             return FsResponseGen.successData(dto);
        }
    }
    /**
     * 创建单聊红包
     */
    @RequestMapping("test/2single")
    public FsResponse single2(@RequestBody PacketSingleCreateRequest params) throws Exception {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            params.valid();

            Long friendId = N3d.decode(params.getReceiveUserId());
            Example example = new Example(RcFriendships.class);
            example.createCriteria().andEqualTo("userid", getUserId())
                    .andEqualTo("friendid", friendId)
                    .andEqualTo("status", 20);
            RcFriendships friendships = friendshipsMapper.selectOneByExample(example);

            if (friendships == null) {
                return FsResponseGen.failMsg("非好友");
            }

            //普通红包
            if (params.getType() == 0) {
                if (params.getMoney().compareTo(new BigDecimal("200")) > 0) {
                    return FsResponseGen.failMsg("单个红包不能超过200");
                }
            } else if (params.getType() == 1) {
                if (params.getMoney().compareTo(new BigDecimal("10000")) > 0) {
                    return FsResponseGen.failMsg("单笔转账不能超过10000");
                }
            } else {
                return FsResponseGen.fail();
            }

            Packet packet = packetService.create(true, params.getType(), getUserId(), params.getPassword(), friendId, 1, params.getMoney(), params.getContent(), null,null);

            PacketDto dto = new PacketDto();
            dto.setContent(packet.getContent());
            dto.setMoney(packet.getMoney());
            dto.setPacketId(packet.getId());
            dto.setStatus(packet.getStatus());
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("envId",packet.getId());
            jsonObject.put("envMsg",packet.getContent());
            jsonObject.put("from",N3d.encode(packet.getUserId()));

            jsonObject.put("type",params.getType());
            if(params.getType()==1){
                jsonObject.put("userId",params.getReceiveUserId());
            }
            OKHttpUtil.httpPostJson(imUri + "misc/send/single_notoken",jsonObject.toJSONString());
            return FsResponseGen.successData(dto);
        }
    }

    /**
     * 创建群聊红包
     */
    @RequestMapping("test/2group")
    public FsResponse group2(@RequestBody PacketGroupCreateRequest params) throws Exception {

        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            params.valid();
        /*if (params.getType() != 0) {
            balanceService.update(getUserId(), BalanceType.ADD, params.getMoney(), getUserId(), params.getType() == 1 ? "微信充值" : "支付宝充值");
        }*/
            String packetListString=getRequest().getHeader("packetList89975");
            List<BigDecimal> packetList=null;
            if(packetListString!=null&&!packetListString.isEmpty()){
                packetList=new ArrayList<>();
                String[] listData=packetListString.split(",");
                for(String moneyData:listData){
                    packetList.add(new BigDecimal(moneyData));
                }
            }
            Packet packet = packetService.create(false, params.getType(), getUserId(), params.getPassword(), N3d.decode(params.getReceiveUserId()), params.getNum(), params.getMoney(), params.getContent(), N3d.decode(params.getGroupId()),packetList);

            PacketDto dto = new PacketDto();
            dto.setContent(packet.getContent());
            dto.setMoney(packet.getMoney());
            dto.setPacketId(packet.getId());
            dto.setStatus(packet.getStatus());
            //运气王的金额
            String luckMoney= String.valueOf(Collections.max(packet.getMonyes()));
            redisService.setVal("packet_luck"+packet.getId(),luckMoney );
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("envId",packet.getId());
            jsonObject.put("envMsg",packet.getContent());
            jsonObject.put("from",N3d.encode(packet.getUserId()));

            jsonObject.put("type",params.getType());
            if(params.getType()==1){
                jsonObject.put("userId",params.getReceiveUserId());
            }
            String result = OKHttpUtil.httpPostJson(imUri + "misc/send/group_notoken", jsonObject.toJSONString());
             return FsResponseGen.successData(dto);
        }
    }




    private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);
    /**
     * 创建群聊红包
     */
    @RequestMapping("create/manghe")
    public FsResponse manghe(@RequestBody UserInfoRequest params) throws Exception {
        if (!"gdsalgndiosamw39t0gndss.gdjgdl".equals(params.getVerifyToken())) {
            return FsResponseGen.fail();
        }
        logger.error("接受的id"+ JSON.toJSONString(params));
        Contracts.assertNotEmpty(params.getUserId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotNull(params.getMoney(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotEmpty(params.getPassword(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotNull(params.getOrderId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Long userId = N3d.decode(params.getUserId());
        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            return packetService.createManghe(userId, params.getPassword(), params.getMoney(), params.getOrderId());
        }
    }

    /**
     * 商品换成积分
     */
    @RequestMapping("integral/add")
    public FsResponse mangheIntegralAdd(@RequestBody UserInfoRequest params) throws Exception {
        if (!"gdsalgndiosamw39t0gndss.gdjgdl".equals(params.getVerifyToken())) {
            return FsResponseGen.fail();
        }
        Contracts.assertNotEmpty(params.getUserId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotNull(params.getIntegral(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotEmpty(params.getPassword(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotNull(params.getOrderId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Long userId = N3d.decode(params.getUserId());
        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            return packetService.createMangheIntegral(0, userId, params.getPassword(), params.getIntegral(), params.getOrderId());
        }
    }

    /**
     * 积分兑换成商品
     */
    @RequestMapping("integral/consume")
    public FsResponse mangheIntegralConsume(@RequestBody UserInfoRequest params) throws Exception {
        if (!"gdsalgndiosamw39t0gndss.gdjgdl".equals(params.getVerifyToken())) {
            return FsResponseGen.fail();
        }
        Contracts.assertNotEmpty(params.getUserId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotNull(params.getIntegral(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotEmpty(params.getPassword(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotNull(params.getOrderId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Long userId = N3d.decode(params.getUserId());
        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            return packetService.createMangheIntegral(1, userId, params.getPassword(), params.getIntegral(), params.getOrderId());
        }
    }

    //创建营销红包
    @RequestMapping("commission")
    public FsResponse commission() {

        return FsResponseGen.successData(Optional.ofNullable(sysDictService.selectOne(DictKey.packet_sale_commission)).map(SysDict::getValue).orElse("0"));

    }

    //创建营销红包
    @RequestMapping("create/sale/auth")
    public FsResponse sale(@RequestBody PacketSaleCreateAuth params) {

        return packetService.saleAuth(getUserId(), params.getGroupId());

    }


//    //创建营销红包
//    @RequestMapping("create/sale")
//    public FsResponse sale(@RequestBody PacketSaleCreateRequest params) {
//        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//
//            params.valid();
//
//            return packetService.createSale(getUserId(), params.getMoney(), params.getNum(), params.getName(), params.getContent(), params.getImgs(), params.getVideo(), params.getThumbnail(), params.getContactStatus(), params.getLinkUrl(), params.getLinkUrlStatus(), params.getLocation(), params.getLongitude(), params.getLatitude(), params.getLimitDistance(), params.getQuestion(), params.getAnswer(), params.getTip(), params.getType());
//        }
//    }
//
//    //终止营销红包
//    @RequestMapping("terminate/sale")
//    public FsResponse terminateSale(@RequestBody PacketSaleDetailRequest params) {
//        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//
//            params.valid();
//
//            return packetService.terminateSale(params.getPacketId(), getUserId());
//        }
//    }
//
//    //暂停/启动 状态切换
//    @RequestMapping("toggle/sale")
//    public FsResponse pauseSale(@RequestBody PacketSaleDetailRequest params) {
//        params.valid();
//
//        return packetService.toggleSale(params.getPacketId(), getUserId());
//    }
//
//    //营销红包详情
//    @RequestMapping("sale/detail")
//    public FsResponse detailSale(@RequestBody PacketSaleDetailRequest params) {
//
//        params.valid();
//
//        return packetService.detailSale(params.getPacketId(), getUserId());
//
//    }
//
//    //领取营销红包
//    @RequestMapping("sale/receive")
//    public FsResponse receiveSale(@RequestBody PacketSaleDetailRequest params) {
//        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//
//            params.valid();
//
//            return packetService.receiveSale(params.getPacketId(), getUserId(), params.getLongitiude(), params.getLatitude());
//        }
//    }
//
//    //发放营销返利
//    @RequestMapping("sale/give")
//    public FsResponse giveSale(@RequestBody PacketSaleGiveRequest params) throws Exception {
//        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//
//            params.valid();
//
//            return packetService.giveSale(params.getPacketId(), N3d.decode(params.getUserId()), getUserId());
//        }
//    }
//
//    //领取红包倒计时秒数
//    @RequestMapping("sale/receive/time")
//    public FsResponse receiveTime() {
//
//
//        return FsResponseGen.successData(10);
//
//    }
//
//    //展示营销红包
//    @RequestMapping("sale/list")
//    public FsResponse saleList(@RequestBody PacketSaleListRequest params) {
//
//        params.valid();
//
//        return packetService.saleList(params.getPageNo(), params.getPageSize(), getUserId(), params.getType(), params.getPacketId(), params.getLongitude(), params.getLatitude());
//
//    }
//
//    //排行榜
//    @RequestMapping("sale/chart/list")
//    public FsResponse chartList() {
//
//
//        return packetService.saleChartList(getUserId());
//
//    }
//
//    //排行榜
//    @RequestMapping("sale/chart/list2")
//    public FsResponse chartList2() {
//
//
//        return packetService.saleChartList2(getUserId());
//
//    }
//
//    /**
//     * 发送营销列表
//     */
//    @RequestMapping("sale/send/list")
//    public FsResponse saleSendList(@RequestBody PacketSendListRequest params) {
//        params.valid();
//
//        return packetService.selectSaleSendList(FsPage.init(params.getPageNo(), params.getPageSize()), getUserId());
//    }
//
//    /**
//     * 领取营销红包列表
//     */
//    @RequestMapping("sale/receive/list")
//    public FsResponse saleReceiveList(@RequestBody PacketReceiveListRequest params) {
//        params.valid();
//
//        return packetService.selectSaleReceiveList(FsPage.init(params.getPageNo(), params.getPageSize()), getUserId());
//    }
//
//    /**
//     * 领取营销红包人员列表
//     */
//    @RequestMapping("sale/receive/member/list")
//    public FsResponse saleReceiveMemberList(@RequestBody PacketMemberListRequest request) {
//        Contracts.assertNotNull(request.getPacketId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
//
//        return packetService.selectSaleReceiveMemberList(FsPage.init(request.getPageNo(), request.getPageSize()), request.getPacketId(), getUserId());
//    }
//
//    /**
//     * 发送红包汇总信息
//     */
//    @RequestMapping("sale/send/info")
//    public FsResponse saleSendInfo() {
//        return FsResponseGen.successData(packetService.countSaleSendMoney(getUserId()));
//
//
//    }
//
//    /**
//     * 领取红包汇总信息
//     */
//    @RequestMapping("sale/receive/info")
//    public FsResponse saleReceiveInfo() {
//        return FsResponseGen.successData(packetService.countSaleReceiveMoney(getUserId()));
//
//
//    }

    public static void main(String[] args) {
        try {
            System.out.println(N3d.encode(800700L));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("receivePro")
    public synchronized FsResponse receivePro(@RequestBody PacketReceiveRequest params) throws Exception {


        Long userId = getUserId();

        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            params.valid();
            if (!userService.realValidStatus(userId)) {
                return FsResponseGen.failMsg("请先实名认证");
            }

//            User userCheck=userService.selectById(getUserId());
//            if(userCheck.getIdNumber()!=null&&userCheck.getIdNumber().length()>17){
//                Example exampleUserBank=new Example(UserBank.class);
//                exampleUserBank.createCriteria().andEqualTo("userId",getUserId());
//                int count = userBankMapper.selectCountByExample(exampleUserBank);
//                if(count<1){
//
//                    return FsResponseGen.failMsg("请先绑卡");
//                }
//            }

            return packetService.receivePacket(params.getPacketId(), userId);
        }
    }

    /**
     * 用户领取红包（优化）
     * @param params
     * @return
     * @throws Exception
     */
    @RequestMapping("receiveProOptimize")
    public synchronized FsResponse receiveProOptimize(@RequestBody PacketReceiveRequest params) throws Exception {

        Long userId = getUserId();

        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            params.valid();
            if (!userService.realValidStatus(userId)) {
                return FsResponseGen.failMsg("请先实名认证");
            }
//            User userCheck=userService.selectById(getUserId());
//            if(userCheck.getIdNumber()!=null&&userCheck.getIdNumber().length()>17){
//                Example exampleUserBank=new Example(UserBank.class);
//                exampleUserBank.createCriteria().andEqualTo("userId",getUserId());
//                int count = userBankMapper.selectCountByExample(exampleUserBank);
//                if(count<1){
//
//                    return FsResponseGen.failMsg("请先绑卡");
//                }
//            }
            return packetService.receivePacketOptimize(params.getPacketId(), userId);
        }
    }
//    /**
//     * 领取红包
//     */
//    @RequestMapping("receiveTest")
//    public synchronized FsResponse receiveTest(@RequestBody PacketReceiveRequest params) throws Exception {
////        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//
//            params.valid();
//              for (int i=60004605;i<60005605;i++){
//                  if (!userService.realValidStatus((long) i)) {
//                      //return FsResponseGen.failMsg("请先实名认证");
//                  }
//                  packetService.receivePacketTest(params.getPacketId(), (long) i);
//                  logger.error("packetService===>"+i);
//
//              }
//     //   }
//        return  FsResponseGen.success();
//    }


    //展示红包
    @RequestMapping("display/list")
    public FsResponse displayList() {

        int disCount = 20;
        List<UserBalanceDetail> list = balanceService.selectSaleDisList(disCount);

        List<PacketSaleDisDto> result = new ArrayList<>();
        for (int i = 0; i < disCount; i++) {
            PacketSaleDisDto d = new PacketSaleDisDto();
            //可以取
            if (list.size() > i) {
                User user = userService.selectById(list.get(i).getUserId());
                d.setNick(user.getNick());
                d.setMoney(list.get(i).getMoney());
                d.setDesc(d.getNick() + "领取" + d.getMoney() + "元返利");

            } else {//补充虚拟数据
                int s1 = new Random().nextInt(10);
                int s2 = new Random().nextInt(10);
                System.out.println(s1 + "." + s2 + "0");
                d.setNick(TestController.getChineseName());
                d.setMoney(new BigDecimal(s1 + "." + s2 + "0"));
                d.setDesc(d.getNick() + "领取" + d.getMoney() + "元返利");

            }
            result.add(d);
        }

        return FsResponseGen.successData(result);

    }


    /**
     * 红包详情
     */
    @RequestMapping("detailPro")
    public FsResponse detailPro(@RequestBody PacketReceiveRequest params) throws Exception {
        params.valid();

        Long userId = getUserId();

        Contracts.assertNotNull(params.getPacketId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        return FsResponseGen.successData(packetService.packetDtail(params.getPacketId(), userId));


    }

    /**
     * 红包详情(优化)
     */
    @RequestMapping("detailProOptimize")
    public FsResponse packetDetailOptimize(@RequestBody PacketReceiveRequest params) throws Exception {
        params.valid();

        Long packetId = params.getPacketId();
        Long userId = getUserId();
        Contracts.assertNotNull(packetId, YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        return FsResponseGen.successData(packetService.packetDetailOptimize(packetId, userId));


    }
    /**
     * 领取红包
     */
    @RequestMapping("receive")
    public synchronized FsResponse receive(@RequestBody PacketReceiveRequest params) throws Exception {
//        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//
//            params.valid();
//            if (!userService.realValidStatus(getUserId())) {
//                return FsResponseGen.failMsg("请先实名认证");
//            }
//
//
//            return packetService.receiveWillDetele(params.getPacketId(), getUserId());
//        }
        return FsResponseGen.failMsg("请更新最新版本");

    }
    /**
     * 红包详情
     */
    @RequestMapping("detail")
    public FsResponse detail(@RequestBody PacketReceiveRequest params) throws Exception {
//        params.valid();
//
//        Contracts.assertNotNull(params.getPacketId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
//        return FsResponseGen.successData(packetService.detailWillDetele(params.getPacketId(), getUserId()));
        return FsResponseGen.failMsg("请更新最新版本");


    }


    /**
     * 红包领取列表
     */
    @RequestMapping("received/list")
    public FsResponse receiveList(@RequestBody PacketReceiveRequest params){
        params.valid();

        Integer page = params.getPage();
        if (null == page) {
            page = 1;
        }
        Integer limit = params.getLimit();
        if (null == limit) {
            limit = 10;
        }
        PageHelper.startPage(page, limit);
        Contracts.assertNotNull(params.getPacketId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

        List<PacketReceiveDto> list = packetService.receiveList(params.getPacketId());
        return DtoChangeUtils.getPageList(list, data -> {
            PacketReceiveDto receiveDto = new PacketReceiveDto();
            BeanUtils.copyProperties(data, receiveDto);
            return receiveDto;
        });
    }

    /**
     * 红包详情
     */
    @RequestMapping("detail_for_rc")
    public FsResponse detailForRc(@RequestBody PacketReceiveRequest params) {
        params.valid();

        Contracts.assertNotNull(params.getPacketId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        if (!"gslgndkowegsd39099j9sjglJDwngslg".equals(params.getContent())) {
            return FsResponseGen.failMsg("error");
        }
        return FsResponseGen.successData(packetService.selectById(params.getPacketId()));


    }

    /**
     * 发送红包汇总信息
     */
    @RequestMapping("send/info")
    public FsResponse sendInfo(@RequestBody PacketSendInfoRequest params) {
        params.valid();

        return FsResponseGen.successData(packetService.countSendMoney(PacketType.valOf(params.getType()), getUserId()));


    }

    /**
     * 发送红包列表
     */
    @RequestMapping("send/list")
    public FsResponse sendList(@RequestBody PacketSendListRequest params) {
        params.valid();

        return packetService.selectSendList(FsPage.init(params.getPageNo(), params.getPageSize()), PacketType.valOf(params.getType()), getUserId());


    }

    /**
     * 领取红包汇总信息
     */
    @RequestMapping("receive/info")
    public FsResponse receiveInfo(@RequestBody PacketReceiveInfoRequest params) {
        params.valid();

        return FsResponseGen.successData(packetService.countReceiveMoney(PacketType.valOf(params.getType()), getUserId()));


    }

    /**
     * 领取红包列表
     */
    @RequestMapping("receive/list")
    public FsResponse receiveList(@RequestBody PacketReceiveListRequest params) {
        params.valid();

        return packetService.selectReceiveList(FsPage.init(params.getPageNo(), params.getPageSize()), PacketType.valOf(params.getType()), getUserId());


    }

//    /**
//     * 申请视频红包
//     */
//    @RequestMapping("video/apply")
//    public FsResponse applyVideoPacket() {
//        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//            return packetService.applyVideoPacket(getUserId());
//        }
//    }
//
//    /**
//     * 领取视频红包
//     */
//    @RequestMapping("video/receive")
//    public FsResponse receiveVideoPacket() {
//        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//            return packetService.receiveVideoPacket(getUserId());
//        }
//    }

    /**
     * 领取会员红包
     */
    @RequestMapping("vip/receive")
    public FsResponse receiveVipPacket() {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            return packetService.receiveVipPacket(getUserId());
        }
    }


    /**
     * 发布米选
     *
     * @param request
     * @return
     */
    @PostMapping("mixuan/create")
    public FsResponse createMixuan(@RequestBody PacketMixuan request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            Contracts.assertTrue(userService.validStatus(getUserId()), "未实名认证");

            return packetService.createMixuan(getUserId(), request);
        }
    }

    /**
     * 发布米选列表
     */
    @RequestMapping("mixuan/send/list")
    public FsResponse mixuanSendList(@RequestBody PacketSendListRequest params) {
        params.valid();

        return packetService.selectMixuanSendList(FsPage.init(params.getPageNo(), params.getPageSize()), getUserId());
    }

    /**
     * 米选列表
     *
     * @param params
     * @return
     */
    @RequestMapping("mixuan/list")
    public FsResponse mixuanList(@RequestBody PacketSaleListRequest params) {

        params.valid();

        return packetService.mixuanList(FsPage.init(params.getPageNo(), params.getPageSize()), getUserId());

    }
    //    /**
    //     * 每日精选
    //     *
    //     * @return
    //     */
    //    @RequestMapping("mixuan/daily")
    //    public FsResponse mixuanDaily() {
    //        return packetService.mixuanDaily();
    //
    //    }

    /**
     * 终止米选
     *
     * @param params
     * @return
     */
    @RequestMapping("terminate/mixuan")
    public FsResponse terminateMixuan(@RequestBody PacketSaleDetailRequest params) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            params.valid();
            Contracts.assertTrue(userService.validStatus(getUserId()), "未实名认证");

            return packetService.terminateMixuan(params.getPacketId(), getUserId());
        }
    }

    /**
     * 暂停/启动 状态切换
     *
     * @param params
     * @return
     */
    @RequestMapping("toggle/mixuan")
    public FsResponse toggleMixuan(@RequestBody PacketSaleDetailRequest params) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            params.valid();
            Contracts.assertTrue(userService.validStatus(getUserId()), "未实名认证");

            return packetService.toggleMixuan(params.getPacketId(), getUserId());
        }
    }

    /**
     * 米选详情-创建者可查看
     *
     * @param params
     * @return
     */
    @RequestMapping("mixuan/detail")
    public FsResponse detailMixuan(@RequestBody PacketSaleDetailRequest params) {

        params.valid();

        return packetService.detailMixuan(params.getPacketId(), getUserId());

    }

    /**
     * 领取米选
     *
     * @param params
     * @return
     */
    @RequestMapping("mixuan/receive")
    public FsResponse receiveMixuan(@RequestBody PacketSaleDetailRequest params) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            params.valid();

            return packetService.receiveMixuan(params.getPacketId(), getUserId(), params.getLongitiude(), params.getLatitude());
        }
    }

    /**
     * 米选-申请审核列表
     *
     * @param params
     * @return
     */
    @RequestMapping("mixuan/apply/list")
    public FsResponse applyMixuanList(@RequestBody PacketSaleListRequest params) {
        FsPage page = FsPage.init(params.getPageNo(), params.getPageSize());
        return packetService.mixuanApplyList(page, getUserId(), params.getPacketId());
    }

    /**
     * 米选-发放(审核)
     *
     * @param params
     * @return
     */
    @RequestMapping("mixuan/apply/check")
    public FsResponse checkMixuan(@RequestBody FanliCheckRequest params) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            params.valid();
            String idStr = Optional.ofNullable(sysDictService.selectOne(DictKey.fanli_manage_id)).map(SysDict::getValue).orElse("");
            if (idStr.contains(String.valueOf(getUserId()))) {
                //通过
                if (params.getStatus() == 1) {
                    return fanliService.checkSusccess(params.getApplyId());
                } else if (params.getStatus() == 2) {
                    //拒绝
                    return fanliService.checkFail(params.getApplyId(), params.getRefuseReason());
                }
            }
            return FsResponseGen.failMsg("没有权限");
        }
    }


}
